﻿using System.IdentityModel.Tokens.Jwt;
using System.Text;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;

namespace JwtBearer;

public static class JwtSecurityExtensions
{
    public static IServiceCollection AddJwtBearer(this IServiceCollection services,IConfiguration configuration)
    {
        var section = configuration.GetSection(nameof(JwtBearerOptions));
        
        // 注册服务
        services.AddTransient<IJwtService, JwtService>()
            .AddSingleton(new JwtSecurityTokenHandler())
            .AddTransient<IHttpContextAccessor,HttpContextAccessor>()
            .Configure<JwtBearerOptions>(section);
         
        // 添加鉴权
        var tokenOptions = section.Get<JwtBearerOptions>()??
                           throw new JwtOptionsNullException(); 
        services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = true,//是否在令牌期间验证签发者
                    ValidateAudience = true,//是否验证接收者
                    ValidateLifetime = true,//是否验证失效时间
                    ValidateIssuerSigningKey = true,//是否验证签名
                    ValidAudience = tokenOptions.Audience,//接收者
                    ValidIssuer = tokenOptions.Issuer,//签发者，签发的Token的人
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(tokenOptions.Key))
                };
            }); 

        return services;
    }

    public static IApplicationBuilder UserJwtBearer(this IApplicationBuilder app)
    {
        // 注意顺序，不然 401
        app.UseAuthentication();
        app.UseAuthorization();
        return app;
    }
}

